package com.ovopark.firecar

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
import android.provider.MediaStore
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.caoustc.okhttplib.okhttp.OkHttpRequestParams
import com.caoustc.okhttplib.okhttp.callback.StringHttpRequestCallback
import com.ovopark.firecar.manager.AppDataAttach
import com.ovopark.firecar.manager.DataManager
import com.ovopark.firecar.okhttp.OkHttpRequest
import com.ovopark.firecar.okhttp.RsGenerator
import com.ovopark.firecar.okhttp.TokenInterceptor
import com.ovopark.firecar.service.WebSocketService
import com.ovopark.firecar.utils.QRCodeUtils
import com.ovopark.firecar.utils.ServiceUtils
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.util.*


class MainActivity : AppCompatActivity() {
    private lateinit var openSocket: TextView
    private lateinit var closeSocket: TextView
    private lateinit var ivCode: ImageView
    val REQUEST_TAKE_PHOTO = 1
//    var currentPhoto: String? = null
    var imageFile : File? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initPhotoError()
        RsGenerator.createNewRetrofit(DataManager.getInstance().getBaseUrl(), TokenInterceptor())
        AppDataAttach.attachContext(application)
        openSocket = findViewById(R.id.open_socket)
        closeSocket = findViewById(R.id.close_socket)
        ivCode = findViewById(R.id.iv_code)
        openSocket.setOnClickListener {
            if (initImageFile()){
                takePictureIntent()
            }else{
                Toast.makeText(this,"初始化失败",Toast.LENGTH_SHORT).show()
            }

//            getList()
//            startSocketService()
        }
        closeSocket.setOnClickListener {
            ServiceUtils.stopWorkingService(this, WebSocketService::class.java)

        }

        ivCode.setImageBitmap(QRCodeUtils.createQrCode(this, "小天", 100, 100, null, null))

    }

    private fun startSocketService() {

        val isServiceRunning: Boolean = ServiceUtils.isServiceWorking(
            applicationContext,
            WebSocketService::class.java
        )
        if (!isServiceRunning) {
            ServiceUtils.startService(this, WebSocketService::class.java)
        }
    }

    override fun onResume() {
        super.onResume()

    }

    fun getList() {
        var param = OkHttpRequestParams()
        param.addBodyParameter("enterpriseId", "000161")
        param.addBodyParameter("storeId", "5517")
        OkHttpRequest.get(
            "https://wanjitest.ovopark.com/mall/storeC/getList",
            param,
            object : StringHttpRequestCallback() {
                override fun onSuccess(data: String?) {
                    super.onSuccess(data)

                }

                override fun onFailure(errorCode: Int, msg: String?) {
                    super.onFailure(errorCode, msg)
                }
            })
    }



    @SuppressLint("QueryPermissionsNeeded")
    fun takePictureIntent() {
        var intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile))
        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
//        if (intent.resolveActivity(packageManager) != null) {
//            var photoFile: File? = null
//            photoFile = createImageFile()
//            if (photoFile != null) {
//                var photoURI: Uri? = null
//                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
//                    /*7.0以上要通过FileProvider将File转化为Uri*/
//                    photoURI = FileProvider.getUriForFile(
//                        this,
//                        getPackageName() + ".fileprovider",
//                        photoFile
//                    )
//                } else {
//                    photoURI = Uri.fromFile(photoFile)
//                }
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
//                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
//            }
//        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_TAKE_PHOTO) {
                if (imageFile!!.exists()){
                    http(imageFile!!)
                    var bitmap : Bitmap = BitmapFactory.decodeFile(imageFile!!.absolutePath)
                    ivCode.setImageBitmap(bitmap)
                }

//            var bundle = data?.extras`
//            var bitmap : Bitmap = bundle?.get("data") as Bitmap
//            ivCode.setImageBitmap(bitmap)
        }
    }

    fun http(file: File) {
        var param = OkHttpRequestParams()
        param.addBodyParameter("model", "res.company")
        param.addBodyParameter("function_name", "_upload_pic")
        param.addBodyParameter(
            "access_token",
            "edca40cff24e88f79b387df31f53b92e"
        )
        param.addBodyParameter("file", file)
        OkHttpRequest.post(
            DataManager.getInstance().getBaseUrl() +
                    DataManager.GET_USER_INFOR,
            param,
            object : StringHttpRequestCallback() {

                override fun onSuccess(data: String?) {
                    super.onSuccess(data)
//                    var result = JSONObject(data).getString("data")
                    Log.i("result", "success result: " + data)
                    var result = JSONObject(data).optString("body")
                    var user = JSONObject(result).optString("Data")
                    var user1 = JSONObject(user).optString("data")
                    var user2 = JSONObject(user1).optString("face")
                    var user3 = JSONObject(user2).optString("data")
                    var user4 = JSONObject(user3).optString("name")
                    Log.i("result","user1: "+user1)
                    Log.i("result","user2: "+user2)
                    Log.i("result","user3: "+user3)
                    Log.i("result","user4: "+user4)
                    Toast.makeText(this@MainActivity,"姓名："+result,Toast.LENGTH_SHORT).show()

                }

                override fun onFailure(errorCode: Int, msg: String?) {
                    super.onFailure(errorCode, msg)
                    Log.i("result", "failed result: " + msg)

                }
            })
    }

    private fun initPhotoError() {
        // android 7.0系统解决拍照的问题
        val builder = VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        builder.detectFileUriExposure()
    }

    fun hasSDCard() : Boolean{
        var state : String = Environment.getExternalStorageState()
        if (Environment.MEDIA_MOUNTED.equals(state)){
            return true
        }
        return false
    }

    fun initImageFile() : Boolean{
        if (hasSDCard()){
            var filePath : String = Environment.getExternalStorageDirectory()
                .absolutePath+"/"+Date().time+".png"
            imageFile = File(filePath)
            imageFile?.let {
                if (!it.exists()) {
                    it.createNewFile()
                }
            }
            return true
        }
        return false
    }


}